package net.israfil.markup.core;

import java.io.IOException;
import java.net.URL;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import net.israfil.foundation.core.Strings;
import net.israfil.markup.model.Markup;

public class JAXBHelperImpl implements JAXBHelper {
	
	public JAXBHelperImpl() {}
	
	public Markup parse(URL markupModelFile, String ... packages){
		JAXBContext jc = null;
		Unmarshaller unmarshaller = null;
		try {
			if (packages == null || packages.length == 0)
				throw new IllegalArgumentException("Must supply relevant package(s) to the parse() method.");
			jc = JAXBContext.newInstance(Strings.concatenate(":",packages));
			unmarshaller = jc.createUnmarshaller();
		} catch (JAXBException je) {
			throw new RuntimeException("Could not create JAXB context or unmarshaller.",je);
		}
		try {
			Markup model= (Markup)((JAXBElement)unmarshaller.unmarshal(markupModelFile.openStream())).getValue();
			return model;
		} catch (IOException ioe) {
			throw new RuntimeException("Could not access "+ markupModelFile + ".  Please check location, permissions, etc.",ioe);
		} catch (JAXBException je) {
			throw new RuntimeException("Could not parse "+ markupModelFile + ".  Please check for validity.",je);
		}
		
	}

}
